package com.rdxer.core.jpaex;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import org.springframework.util.StringUtils;

import javax.persistence.AttributeConverter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ListToJsonConverter implements AttributeConverter<List<String>, String> {

    ObjectMapper objectMapper = new ObjectMapper();
    TypeFactory typeFactory = objectMapper.getTypeFactory();


    @Override
    public String convertToDatabaseColumn(List<String> o) {
        if (o != null) {
            try {
                return objectMapper.writeValueAsString(o);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }
        return "[]";
    }


    @Override
    public List<String> convertToEntityAttribute(String s) {
        if (!StringUtils.isEmpty(s)) {
            try {
                return objectMapper.readValue(s, typeFactory.constructCollectionType(List.class, String.class));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return new ArrayList<>();
    }
}